package com.gl.common.mybatis;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 主数据源mybatis配置
 * @author 
 *
 */
@Configuration
@EnableConfigurationProperties(JdbcPrimaryProperties.class)
@EnableTransactionManagement
public class MybatisPrimaryConfig {
	private static Logger logger = LoggerFactory.getLogger(MybatisPrimaryConfig.class);
	
	@Autowired
	private JdbcPrimaryProperties jdbcPrimaryProperties;
	
	/**
	 * 创建主数据源
	 * @return
	 * @throws SQLException 
	 */
	@Primary
	@Bean(name="dataSource",initMethod="init" ,destroyMethod="close")
	public DataSource dataSource() {
		logger.info("===>>>开始初始化主数据源:[dataSource]");
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName(jdbcPrimaryProperties.getDriverClassName());
	    druidDataSource.setUrl(jdbcPrimaryProperties.getUrl());
	    druidDataSource.setUsername(jdbcPrimaryProperties.getUsername());
	    druidDataSource.setPassword(jdbcPrimaryProperties.getPassword());
	    druidDataSource.setInitialSize(jdbcPrimaryProperties.getInitialSize());
	    druidDataSource.setMinIdle(jdbcPrimaryProperties.getMinIdle());
	    druidDataSource.setMaxActive(jdbcPrimaryProperties.getMaxActive());
	    druidDataSource.setMaxWait(jdbcPrimaryProperties.getMaxWait()); 
	    druidDataSource.setTimeBetweenEvictionRunsMillis(jdbcPrimaryProperties.getTimeBetweenEvictionRunsMillis()); 
	    druidDataSource.setMinEvictableIdleTimeMillis(jdbcPrimaryProperties.getMinEvictableIdleTimeMillis()); 
	    druidDataSource.setValidationQuery(jdbcPrimaryProperties.getValidationQuery()); 
	    druidDataSource.setTestWhileIdle(jdbcPrimaryProperties.isTestWhileIdle());
	    druidDataSource.setTestOnBorrow(jdbcPrimaryProperties.isTestOnBorrow()); 
	    druidDataSource.setTestOnReturn(jdbcPrimaryProperties.isTestOnReturn()); 
	    druidDataSource.setPoolPreparedStatements(jdbcPrimaryProperties.isPoolPreparedStatements()); 
	    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcPrimaryProperties.getMaxPoolPreparedStatementPerConnectionSize()); 
	    druidDataSource.setRemoveAbandoned(jdbcPrimaryProperties.isRemoveAbandoned());
	    druidDataSource.setRemoveAbandonedTimeout(jdbcPrimaryProperties.getRemoveAbandonedTimeout());
	    druidDataSource.setLogAbandoned(jdbcPrimaryProperties.isLogAbandoned());
	  
		return druidDataSource;
	}
	
	/**
	 * 事务管理器
	 * @return
	 */
	@Primary
	@Bean(name="transactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
	
	/**
	 * 配置sqlSessionFactory
	 * 在mybatis的配置文件中配置分页拦截器
	 * 
	 * @return
	 * @throws Exception
	 */
	@Primary
	@Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
		logger.info("===>>>开始初始化主数据源mybatis的SqlSessionFactory");
		
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:config/mybatis/mybatis-config.xml"));
        try {
        	sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/**/*-mapper.xml"));
			return sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			logger.error("===>>>初始化主数据源mybatis的sqlSessionFactory失败:"+e.getMessage());
			e.printStackTrace();
			throw new RuntimeException(e);
		}
    }
	
	/**
	 * 配置SqlSessionTemplate
	 * @return
	 */
	@Primary
	@Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate() {
        return new SqlSessionTemplate(sqlSessionFactoryBean());
    }
	
}
